package com.sbpm.crmbpm.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;

import com.sbpm.crmbpm.client.deprecforms.FormFactory;
import com.sbpm.crmbpm.client.deprecforms.OnFinishCallBack;
import com.sbpm.crmbpm.client.deprecforms.ProcessForm;
import com.sbpm.crmbpm.client.grid.TaskGrid;
import com.sbpm.crmbpm.client.services.ProcessService;
import com.sbpm.crmbpm.client.services.ProcessServiceAsync;
import com.sbpm.crmbpm.client.services.UserService;
import com.sbpm.crmbpm.client.services.UserServiceAsync;
import com.sbpm.crmbpm.client.util.SimpleAsyncCallback;
import com.sbpm.crmbpm.shared.data.TaskInfo;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.widget.core.client.FramedPanel;
import com.sencha.gxt.widget.core.client.box.*;
import com.sencha.gxt.widget.core.client.button.ButtonBar;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.MarginData;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @deprecated
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class HelloGXT implements EntryPoint {
    /**
     * The message displayed to the user when the server cannot be reached or
     * returns an error.
     */
    private static final String SERVER_ERROR = "An error occurred while "
            + "attempting to contact the server. Please check your network "
            + "connection and try again.";

    /**
     * Create a remote service proxy to talk to the server-side Greeting service.
     */
    private final ProcessServiceAsync processService = GWT.create(ProcessService.class);

    private final UserServiceAsync userService = GWT.create(UserService.class);

    private ButtonBar buttonBar;

    private FramedPanel panel;

    private com.sencha.gxt.widget.core.client.grid.Grid grid;
    private ListBox usersComboBox;

    private FormFactory formFactory = new FormFactory();

    public Widget createPanel() {

        if( panel == null )
        {
            panel = new FramedPanel();
            panel.setHeadingText("jBPM");
//            panel.setPixelSize(400, 300);
            //panel.setCollapsible(true);
            panel.setLayoutData(new MarginData(10));

        }

        if (buttonBar == null)
        {
            buttonBar = new ButtonBar();
            buttonBar.setMinButtonWidth(75);
            buttonBar.getElement().setMargins(10);
//            buttonBar.setHeight( 40 );

            TextButton b = new TextButton("Create money transfer process");
            b.addSelectHandler(new SelectHandler() {
                public void onSelect(SelectEvent event) {

                    processService.createMoneyTransferProcessInstance(new AsyncCallback<Long>() {
                        @Override
                        public void onFailure(Throwable caught) {
                            AlertMessageBox d = new AlertMessageBox("Error", "Result - " + caught.getMessage());
                            d.show();
                        }

                        @Override
                        public void onSuccess(Long result) {
                            MessageBox d = new MessageBox("Success", "Result - " + result);
                            d.show();
                        }
                    });
                }
            });
            buttonBar.add(b);

            TextButton processTaskButton = new TextButton( "Process task" );
            processTaskButton.addSelectHandler(new SelectHandler() {
                @Override
                public void onSelect(SelectEvent event) {
                    if (grid.getSelectionModel().getSelectedItem() != null && usersComboBox.getSelectedIndex() > -1) {

                        TaskInfo task = ( TaskInfo ) grid.getSelectionModel().getSelectedItem();

                        final Long taskId = task.getId();
                        if( "Ready".equals( task.getStatus() ) || "Reserved".equals( task.getStatus() ) )
                        {
                            processService.startTask( taskId, usersComboBox.getValue( usersComboBox.getSelectedIndex() ), new SimpleAsyncCallback< Map< String, Object > >()
                            {
                                @Override
                                public void onSuccess( Map< String, Object > result )
                                {
                                    startTask( result, taskId );
                                }
                            } );
                        }
                        else if( "InProgress".equals( task.getStatus()  ) )
                        {
                            processService.getTaskData( taskId, new SimpleAsyncCallback< Map< String, Object > >()
                            {
                                @Override
                                public void onSuccess( Map< String, Object > result )
                                {
                                    startTask( result, taskId );
                                }
                            } );
                        }
                        /*processService.moveFlow(((TaskInfo) grid.getSelectionModel().getSelectedItem()).getId(), usersComboBox.getValue(), new AsyncCallback() {
                            @Override
                            public void onFailure(Throwable caught) {
                                MessageBox box = new MessageBox("Fail " + caught.getMessage());
                                box.show();
                            }

                            @Override
                            public void onSuccess(Object result) {
                                MessageBox box = new MessageBox("Success");
                                box.show();
                            }
                        });*/
                    }
                }
            });
            buttonBar.add( processTaskButton );
        }

        VerticalLayoutContainer verticalLayoutContainer = new VerticalLayoutContainer();
//        panel.setHeight( "100%" );
//        verticalLayoutContainer.setHeight( "100%" );


        verticalLayoutContainer.add(buttonBar, new VerticalLayoutContainer.VerticalLayoutData(0, 40, new Margins(4)));

        ListBox box = new ListBox(  );
        //box.

        usersComboBox = new ListBox();

        usersComboBox.addChangeHandler( new ChangeHandler()
        {
            @Override
            public void onChange(ChangeEvent event)
            {
                refreshTaskGrid( usersComboBox.getItemText( usersComboBox.getSelectedIndex() ) );
            }
        } );
        userService.getUsers( new AsyncCallback<List<String>>() {
            @Override
            public void onFailure(Throwable throwable) {

            }

            @Override
            public void onSuccess(List<String> strings)
            {
                for( String user : strings )
                {
                    usersComboBox.addItem( user );
                }

            }
        } );

        verticalLayoutContainer.add( usersComboBox, new VerticalLayoutContainer.VerticalLayoutData(100, 40, new Margins(4)) );

        TaskGrid taskGrid = new TaskGrid();

        grid = taskGrid.createTaskGrid( new ArrayList() );
        grid.setHeight( "300px" );
        grid.setPixelSize(200, 200);

        verticalLayoutContainer.add(grid, new VerticalLayoutContainer.VerticalLayoutData(500, 300, new Margins(4)));

        panel.setWidget( verticalLayoutContainer );


        return panel;
    }

    private void startTask( Map< String, Object > result, Long taskId )
    {
        String taskName = ( ( TaskInfo ) grid.getSelectionModel().getSelectedItem() ).getName();
        ProcessForm processForm = formFactory.createForm( taskName, taskId, usersComboBox.getValue( usersComboBox.getSelectedIndex() ) );
        processForm.setData( result );
        processForm.setOnFinishCallBack( new OnFinishCallBack()
        {
            @Override
            public void onFinish()
            {
                refreshTaskGrid();
            }
        } );
        processForm.show();
    }

    private void refreshTaskGrid()
    {
        refreshTaskGrid( usersComboBox.getItemText( usersComboBox.getSelectedIndex() ) );
    }

    private void refreshTaskGrid( String user )
    {
        processService.getTaskList(user, new AsyncCallback<List<TaskInfo>>() {
            @Override
            public void onFailure(Throwable caught) {
            }

            @Override
            public void onSuccess(List<TaskInfo> result) {
                grid.getStore().clear();
                grid.getStore().addAll( result );

                //grid.reconfigure( grid.getStore(), grid.getColumnModel() );
                grid.getView().refresh( false );
//                MessageBox box = new MessageBox( "store size = " + grid.getStore().size() + ", result size = " + result.size() );
//                box.show();
            }
        });
    }

    public void onModuleLoad() {
        RootPanel.get().add(createPanel());



       /* TaskGrid taskGrid = new TaskGrid();
        com.sencha.gxt.widget.core.client.grid.Grid grid = taskGrid.createTaskGrid();
		RootPanel.get().add(grid);*/

    }


}
